using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;
using CodePlex.DnD4eCampaignManager.DnD4e;
using CodePlex.DnD4eCampaignManager.DnD4e.Interfaces;
using CodePlex.DnD4eCampaignManager.Repositories.Interfaces;

namespace CodePlex.DnD4eCampaignManager.Repositories
{
    public class PlayerCharacterRepository : IPlayerCharacterRepository
    {
        private const string CHARACTER_FOLDER = "Characters";

        public PlayerCharacterRepository()
        {
            if ( !Directory.Exists(CHARACTER_FOLDER) )
            {
                Directory.CreateDirectory(CHARACTER_FOLDER);
            }
        }

        public ReadOnlyCollection<string> GetAllNames()
        {
            List<string> characterNames = new List<string>();
            foreach ( string file in Directory.GetFiles(CHARACTER_FOLDER, "*.pc") )
            {
                characterNames.Add(file.Replace(".pc", string.Empty).Replace("\\", string.Empty).Replace(CHARACTER_FOLDER, string.Empty));
            }
            return characterNames.AsReadOnly();
        }

        public IPlayerCharacter GetByName(string playerCharacterName)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof ( PlayerCharacter ));
            using ( TextReader textReader = new StreamReader(string.Format("{1}\\{0}.pc", playerCharacterName, CHARACTER_FOLDER)) )
            {
                PlayerCharacter playerPlayerCharacter = xmlSerializer.Deserialize(textReader) as PlayerCharacter;
                if ( playerPlayerCharacter != null )
                {
                    return playerPlayerCharacter;
                }
            }
            return null;
        }

        public void Save(IPlayerCharacter playerCharacter)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof ( PlayerCharacter ));
            using ( TextWriter textWriter = new StreamWriter(string.Format("{1}\\{0}.pc", playerCharacter.Name, CHARACTER_FOLDER)) )
            {
                xmlSerializer.Serialize(textWriter, playerCharacter);
            }
        }
    }
}